package libs

import (
	"crypto/md5"
	"fmt"
	"io"
	"io/ioutil"
	"mime/multipart"
	"os"
	"regexp"
	"time"
)

func SaveFile(fileHeader *multipart.FileHeader) (name string, err error) {
	file, err := fileHeader.Open()
	defer file.Close()
	if err != nil {
		return "", err
	}
	//生成MD5后的/aa/bb/cc/dd/ee/的目录
	body, err := ioutil.ReadAll(file)
	if err != nil {
		return "", err
	}
	md5str := fmt.Sprintf("%x", md5.Sum(body))
	path := Conf.DirUpload + "/" + md5str[0:2] + "/" + md5str[2:4] + "/" + md5str[4:6]
	err = MkdirByPath(path)
	if err != nil {
		return "", err
	}
	//获取文件扩展名,文件大小
	reg := regexp.MustCompile(`\.[a-zA-Z_]{3,5}$`)
	ext := reg.FindString(fileHeader.Filename)
	//ext = strings.ToLower(ext)
	//size:=files[i].Size
	name = md5str + ext

	filename := path + "/" + name
	file, err = fileHeader.Open()
	dst, err := os.Create(filename)
	defer dst.Close()

	if err != nil {
		return "", err
	}
	if _, err := io.Copy(dst, file); err != nil {
		return "", err
	}
	if err != nil {
		return "", err
	}
	if RedisClient != nil {
		//使用list来保存日期与KEY的列表 （用于删除只上传没保存的文件，和浏览每天上传的文件信息）k=日期,v=key
		t := time.Now().Format("060102")
		err = RedisSetSet(t, name)
		if err != nil {
			return "", err
		}
		err = RedisSetSet(name, "0")
		if err != nil {
			return "", err
		}
	}
	return name, err
}
